<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-alert title="添加商品信息" type="info" center show-icon> </el-alert>
      <el-steps
        :active="activeIndex - 0"
        finish-status="success"
        simple
        style="margin-top: 20px"
        align-center
      >
        <el-step title="基本信息" icon="el-icon-edit"></el-step>
        <el-step title="商品参数" icon="el-icon-upload"></el-step>
        <el-step title="商品属性" icon="el-icon-picture"></el-step>
        <el-step title="商品图片" icon="el-icon-picture"></el-step>
        <el-step title="商品内容" icon="el-icon-picture"></el-step>
        <el-step title="完成" icon="el-icon-picture"></el-step>
      </el-steps>
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRules"
        labal-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          tab-position="left"
          :before-leave="beforTabLeave"
          @tab-click="handleTabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                expand-trigger="hover"
                :options="cateList"
                :props="cateProps"
                v-model="addForm.goods_cat"
                @change="handleCascaderChange"
                clearable
              >
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in manyTableData"
              :key="index"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="subItem"
                  border
                  v-for="(subItem, subIndex) in item.attr_vals"
                  :key="subIndex"
                >
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="(item, index) in onlyTableData"
              :key="index"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headers"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"> </quill-editor>
            <el-button type="primary" style="margin-top: 10px" @click="onSubmit"
              >提交</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 展示图片的对话框 -->
    <el-dialog title="提示" :visible.sync="previewDialogVisible" width="50%">
      <img :src="previewUrl" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script>
// 引入 lodash
import { cloneDeep } from 'lodash'
export default {
  data () {
    return {
      activeIndex: 0,
      addForm: {
        goods_introduce: '', // 商品介绍
        goods_name: '', // 商品名称
        goods_price: 0, // 价格
        goods_number: 0, // 数量
        goods_weight: 0, // 重量
        goods_cat: [], // 分类
        pics: [], // 存储图片对象
        attrs: [] // 存储商品信息对象
      },
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ], // 商品名称
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ], // 价格
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ], // 数量
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ], // 重量
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ] // 分类
      },
      selectedKeys: [],
      // 商品分类列表
      cateList: [],
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 动态参数列表数据
      manyTableData: [],
      // 静态属性列表数据
      onlyTableData: [],
      // 上传图片的URL地址
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 上传图片需要请求报文头
      headers: {
        Authorization: window.sessionStorage.getItem('token')
      },
      previewUrl: '', // 图片路径
      previewDialogVisible: false // 是否弹出展示图片的对话框
    }
  },
  computed: {
  // 获取分类ID
    cateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  },
  created () {
    this.getCateList()
    // todo:测试语句
    // this.addForm.goods_cat = [1, 3, 6]
    // this.activeIndex = '2'
    // this.handleTabClick()
  },
  methods: {
    beforTabLeave (activeName, oldActiveName) {
      console.log('即将离开的标签页名字是：' + oldActiveName)
      console.log('即将进入的标签页名字是：' + activeName)
      // return false

      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类！')
        return false
      }
    },
    // 级联选择器选中项变化，会触发这个函数
    handleCascaderChange () {
      // console.log(this.addForm.goods_cat)
      // 判断分类里面是否有三级分类，如果没有则清空文本框
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    async handleTabClick () {
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'many' } })
        // console.log(this.cateId)
        res.data.forEach(t => {
          t.attr_vals = t.attr_vals.length === 0 ? [] : t.attr_vals.split(' ')
        })
        this.manyTableData = res.data
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: 'only' } })
        this.onlyTableData = res.data
      }
    },

    // 异步获取商品列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 3 }// 设定获得第几级的数据
      })
      this.cateList = res.data // 将获得的数据传给商品分类列表
    },
    // 图片处理函数
    handleRemove (file, fileList) {
      console.log(file)
      const tmpPath = file.response.data.tmp_path
      // 过滤
      this.addForm.pics = this.addForm.pics.filter(t => t.pic !== tmpPath)
    },
    // 图片展示
    handlePreview (file) {
      console.log(file)
      this.previewUrl = file.response.data.url
      this.previewDialogVisible = true
    },
    // 图片上传后执行的函数
    handleSuccess (response, file, fileList) {
      this.addForm.pics.push({
        pic: response.data.tmp_path
      })
    },
    // 添加商品
    onSubmit () {
      // 商品信息校验
      this.$refs.addFormRules.validate(async (isOk, error) => {
        console.log(isOk)
        if (isOk) {
          this.$message({
            message: '验证成功',
            type: 'success',
            showClose: true,
            duration: 3000
          })
          const formData = cloneDeep(this.addForm)
          formData.goods_cat = this.addForm.goods_cat.join(',')
          this.manyTableData.forEach(t => {
            this.addForm.attrs.push({
              attr_id: t.attr_id,
              attr_value: t.attr_vals
            })
          })
          this.onlyTableData.forEach(t => {
            this.addForm.attrs.push({
              attr_id: t.attr_id,
              attr_value: t.attr_vals
            })
          })
          formData.attrs = this.addForm.attrs
          const { data: res } = await this.$http.post('goods', formData)
          if (res.meta.status !== 201) {
            this.$message({
              message: '新增失败',
              type: 'error',
              showClose: true,
              duration: 3000
            })
          } else {
            this.$message({
              message: '新增成功',
              type: 'success',
              showClose: true,
              duration: 3000
            })
            this.$router.push('/goods')
          }
        } else {
          this.$message({
            message: '验证失败',
            type: 'error',
            showClose: true,
            duration: 3000
          })
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
</style>
